package logic

import (
	"context"
	"fmt"
	"wangwang/models/cache"
	"wangwang/models/mysql"
	"wangwang/pkg"

	"wangwang/wangwangrpc/internal/svc"
	"wangwang/wangwangrpc/wangwangrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *wangwangrpc.LoginRequest) (*wangwangrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	images := cache.Rdb.Get(l.ctx, "captcha"+"login"+in.Mobile)
	if images.Val() != in.SmsCode {
		return nil, fmt.Errorf("图形证码错误,请重新输入")
	}

	var user mysql.User
	err := mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user).Error
	if err != nil {
		return nil, fmt.Errorf("登录失败")
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("未注册用户不允许登录")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误,登录失败")
	}

	cache.Rdb.Del(l.ctx, "sendSms"+"login"+in.Mobile)
	cache.Rdb.Del(l.ctx, "captcha"+"login"+in.Mobile)
	return &wangwangrpc.LoginResponse{
		Id: int64(user.ID),
	}, nil
}
